import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import * as api from '../utils/api';
import { TournamentConfig, RoundConfig } from '../types';

const RoundManagePage: React.FC = () => {
  const navigate = useNavigate();
  const [config, setConfig] = useState<TournamentConfig | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);
  const [showAddForm, setShowAddForm] = useState(false);
  const [editingRound, setEditingRound] = useState<RoundConfig | null>(null);
  const [formData, setFormData] = useState<RoundConfig>({
    name: '',
    display_name: '',
    groups_count: 1,
    teams_per_group: 2,
    advance_count: 1,
    type: 'main'
  });

  useEffect(() => {
    loadConfig();
  }, []);

  const loadConfig = async () => {
    try {
      setLoading(true);
      const response = await api.getTournamentConfig();
      if (response.success && response.config) {
        setConfig(response.config);
      } else {
        setError('获取配置失败');
      }
    } catch (err) {
      setError('加载配置失败');
      console.error('加载配置失败:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleAddRound = () => {
    setFormData({
      name: '',
      display_name: '',
      groups_count: 1,
      teams_per_group: 2,
      advance_count: 1,
      type: 'main'
    });
    setEditingRound(null);
    setShowAddForm(true);
  };

  const handleEditRound = (round: RoundConfig) => {
    setFormData({ ...round });
    setEditingRound(round);
    setShowAddForm(true);
  };

  const handleSaveRound = async () => {
    try {
      setSaving(true);
      setError(null);

      if (editingRound) {
        // 更新轮次
        const response = await api.updateRound(editingRound.name, { round: formData });
        if (response.success && response.config) {
          setConfig(response.config);
          setShowAddForm(false);
          setEditingRound(null);
        } else {
          setError(response.error || '更新轮次失败');
        }
      } else {
        // 添加轮次
        const response = await api.addRound({ round: formData });
        if (response.success && response.config) {
          setConfig(response.config);
          setShowAddForm(false);
        } else {
          setError(response.error || '添加轮次失败');
        }
      }
    } catch (err) {
      setError('保存轮次失败');
      console.error('保存轮次失败:', err);
    } finally {
      setSaving(false);
    }
  };

  const handleDeleteRound = async (roundName: string) => {
    if (!confirm(`确定要删除轮次 "${roundName}" 吗？`)) return;

    try {
      setSaving(true);
      setError(null);

      const response = await api.deleteRound(roundName);
      if (response.success && response.config) {
        setConfig(response.config);
      } else {
        setError(response.error || '删除轮次失败');
      }
    } catch (err) {
      setError('删除轮次失败');
      console.error('删除轮次失败:', err);
    } finally {
      setSaving(false);
    }
  };

  const handleFormChange = (field: keyof RoundConfig, value: any) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-900 via-purple-900 to-indigo-900 flex items-center justify-center">
        <div className="text-white text-xl">加载中...</div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-900 via-purple-900 to-indigo-900 p-4">
      <div className="max-w-6xl mx-auto">
        {/* 头部 */}
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center space-x-4">
            <button
              onClick={() => navigate('/tournament')}
              className="bg-gray-600 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded transition-colors duration-200"
            >
              ← 返回
            </button>
            <h1 className="text-3xl font-bold text-white">轮次管理</h1>
          </div>
          <button
            onClick={handleAddRound}
            disabled={saving}
            className="bg-green-600 hover:bg-green-700 disabled:bg-gray-600 text-white font-bold py-2 px-4 rounded transition-colors duration-200"
          >
            添加轮次
          </button>
        </div>

        {/* 错误信息 */}
        {error && (
          <div className="bg-red-500/20 border border-red-500 text-red-100 px-4 py-3 rounded mb-6">
            {error}
          </div>
        )}

        {/* 轮次列表 */}
        <div className="bg-white/10 backdrop-blur-sm rounded-2xl p-6">
          <h2 className="text-xl font-bold text-white mb-4">当前轮次配置</h2>
          
          {config?.rounds && config.rounds.length > 0 ? (
            <div className="space-y-4">
              {config.rounds.map((round, index) => (
                <div key={round.name} className="bg-white/5 rounded-lg p-4 border border-white/10">
                  <div className="flex items-center justify-between">
                    <div className="flex-1">
                      <div className="flex items-center space-x-4 mb-2">
                        <span className="text-lg font-semibold text-white">
                          {index + 1}. {round.display_name}
                        </span>
                        <span className={`px-2 py-1 rounded text-xs font-medium ${
                          round.type === 'main' ? 'bg-blue-500/20 text-blue-300' :
                          round.type === 'revival' ? 'bg-yellow-500/20 text-yellow-300' :
                          'bg-purple-500/20 text-purple-300'
                        }`}>
                          {round.type === 'main' ? '主要比赛' : 
                           round.type === 'revival' ? '复活赛' : '决赛'}
                        </span>
                      </div>
                      <div className="text-sm text-gray-300 space-y-1">
                        <div>轮次名称: <span className="text-white">{round.name}</span></div>
                        <div>对战组数: <span className="text-white">{round.groups_count}</span></div>
                        <div>每组队伍数: <span className="text-white">{round.teams_per_group}</span></div>
                        <div>晋级队伍数: <span className="text-white">{round.advance_count}</span></div>
                      </div>
                    </div>
                    <div className="flex space-x-2">
                      <button
                        onClick={() => handleEditRound(round)}
                        disabled={saving}
                        className="bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 text-white font-bold py-1 px-3 rounded text-sm transition-colors duration-200"
                      >
                        编辑
                      </button>
                      <button
                        onClick={() => handleDeleteRound(round.name)}
                        disabled={saving}
                        className="bg-red-600 hover:bg-red-700 disabled:bg-gray-600 text-white font-bold py-1 px-3 rounded text-sm transition-colors duration-200"
                      >
                        删除
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center text-gray-400 py-8">
              暂无轮次配置，请添加轮次
            </div>
          )}
        </div>

        {/* 添加/编辑轮次表单 */}
        {showAddForm && (
          <div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50">
            <div className="bg-white rounded-lg p-6 w-full max-w-md">
              <h3 className="text-lg font-bold text-gray-900 mb-4">
                {editingRound ? '编辑轮次' : '添加轮次'}
              </h3>
              
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    轮次名称
                  </label>
                  <input
                    type="text"
                    value={formData.name}
                    onChange={(e) => handleFormChange('name', e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="例如: round1_main"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    显示名称
                  </label>
                  <input
                    type="text"
                    value={formData.display_name}
                    onChange={(e) => handleFormChange('display_name', e.target.value)}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="例如: 第一轮晋级赛"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    轮次类型
                  </label>
                  <select
                    value={formData.type}
                    onChange={(e) => handleFormChange('type', e.target.value as 'main' | 'revival' | 'final')}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="main">主要比赛</option>
                    <option value="revival">复活赛</option>
                    <option value="final">决赛</option>
                  </select>
                </div>

                <div className="grid grid-cols-3 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      对战组数
                    </label>
                    <input
                      type="number"
                      min="1"
                      value={formData.groups_count}
                      onChange={(e) => handleFormChange('groups_count', parseInt(e.target.value))}
                      className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      每组队伍数
                    </label>
                    <input
                      type="number"
                      min="2"
                      value={formData.teams_per_group}
                      onChange={(e) => handleFormChange('teams_per_group', parseInt(e.target.value))}
                      className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      晋级队伍数
                    </label>
                    <input
                      type="number"
                      min="1"
                      value={formData.advance_count}
                      onChange={(e) => handleFormChange('advance_count', parseInt(e.target.value))}
                      className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                  </div>
                </div>
              </div>

              <div className="flex space-x-3 mt-6">
                <button
                  onClick={handleSaveRound}
                  disabled={saving || !formData.name || !formData.display_name}
                  className="flex-1 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 text-white font-bold py-2 px-4 rounded transition-colors duration-200"
                >
                  {saving ? '保存中...' : (editingRound ? '更新' : '添加')}
                </button>
                <button
                  onClick={() => setShowAddForm(false)}
                  disabled={saving}
                  className="flex-1 bg-gray-600 hover:bg-gray-700 disabled:bg-gray-400 text-white font-bold py-2 px-4 rounded transition-colors duration-200"
                >
                  取消
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default RoundManagePage;
